package com.piece.admin.controller.system;

import com.piece.admin.api.dto.SysConfigDTO;
import com.piece.admin.model.TbSysConfig;
import com.piece.admin.service.TbSysConfigService;
import com.piece.admin.support.SiteConfigSupport;
import com.piece.core.framework.annotation.permission.AclPermission;
import com.piece.core.framework.annotation.permission.SubmitPermission;
import com.piece.core.framework.constant.ExceptionConstants;
import com.piece.core.framework.support.bootstrap.DataTable;
import com.piece.core.framework.support.bootstrap.QueryTable;
import com.piece.core.framework.support.bootstrap.Valid;
import com.piece.core.framework.support.convert.Convert;
import com.piece.core.framework.support.response.AjaxResponse;
import com.piece.core.framework.util.basic.I18nUtil;
import com.piece.core.framework.util.math.SequenceUtil;
import com.piece.core.framework.util.string.StringUtil;
import com.piece.core.framework.util.file.FileUtil;
import com.piece.core.web.controller.FrameWorkController;
import com.piece.file.client.FileClientFactory;
import com.piece.module.file.util.excel.ExcelParam;
import com.piece.module.file.util.excel.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.io.InputStream;
import java.util.List;

@RestController
@Api(tags = {"系统参数管理"})
@RequestMapping("/api/system/config")
public class SysConfigController extends FrameWorkController {

    @Resource
    private FileClientFactory fileClientFactory;

    @Resource
    private TbSysConfigService tbSysConfigService;

    @Resource
    private SiteConfigSupport siteConfigSupport;

    @PostMapping("/list")
    @ApiOperation(value = "查询参数列表")
    @ApiImplicitParam(value = "查询条件", dataTypeClass = QueryTable.class, type = "body")
    public List list() {
        QueryTable queryTable = initTable();
        DataTable dataTable = tbSysConfigService.findPage(queryTable);
        return dataTable.getData();
    }

    @PostMapping("/table")
    @AclPermission(code = "system:config:view")
    @ApiOperation(value = "查询参数分页数据")
    @ApiImplicitParam(value = "查询条件", dataTypeClass = QueryTable.class, type = "body")
    public AjaxResponse table() {
        QueryTable queryTable = initTable();
        DataTable dataTable = tbSysConfigService.findPage(queryTable);
        return success(dataTable);
    }

    @GetMapping("/load")
    @AclPermission(code = "system:config:view")
    @ApiOperation(value = "生成参数表单数据")
    @ApiImplicitParam(name = "id", value = "参数主键")
    public AjaxResponse load() {
        long id = Convert.toLong(getRequest().getParameter("id"), 0L);
        TbSysConfig config = new TbSysConfig();
        if (id != 0) {
            config = tbSysConfigService.findById(id);
        }
        return success(config);
    }

    @SubmitPermission
    @PostMapping("/save")
    @AclPermission(code = "system:config:add,system:config:edit")
    @ApiOperation(value = "保存参数表单数据")
    @ApiImplicitParam(value = "参数表单", dataTypeClass = TbSysConfig.class, type = "body")
    public AjaxResponse save() {
        TbSysConfig config = new TbSysConfig();
        try {
            initDB(config);
            tbSysConfigService.insertOrUpdate(config);
            // 刷新站点变量
            siteConfigSupport.reload(config);
            return success(I18nUtil.message(ExceptionConstants.SAVE_SUCCESS), null);
        } catch (Exception e) {
            return error(I18nUtil.message(ExceptionConstants.SAVE_FAILURE), e.getMessage());
        }
    }

    @SubmitPermission
    @PostMapping("/delete")
    @AclPermission(code = "system:config:delete")
    @ApiOperation(value = "删除参数")
    @ApiImplicitParam(name = "ids", value = "参数ID集合")
    public AjaxResponse delete() throws Exception {
        String ids = getRequest().getParameter("ids");
        if (StringUtil.isNotEmpty(ids)) {
            tbSysConfigService.delete(Convert.toLongArray(ids));
        }
        return success(I18nUtil.message(ExceptionConstants.DELETE_SUCCESS), null);
    }

    @SubmitPermission
    @PostMapping("/export")
    @AclPermission(code = "system:config:edit")
    @ApiOperation(value = "导出参数文件")
    @ApiImplicitParam(value = "查询条件", dataTypeClass = QueryTable.class, type = "body")
    public AjaxResponse export() {
        try {
            QueryTable queryTable = initTable();
            DataTable dataTable = tbSysConfigService.findPage(queryTable);
            List<TbSysConfig> list = dataTable.getData();
            ExcelParam param = ExcelParam.builder()
                    .sheetName("参数列表")
                    .convertType(SysConfigDTO.class)
                    .data(list)
                    .build();
            InputStream is = ExcelUtil.write(param);
            String fileName = "导出参数列表_" + SequenceUtil.uuid() + ".xlsx";
            String filePath = fileClientFactory.getNative().writeToLocalStore(FileUtil.toByte(is), FileUtil.getTempPath(), fileName);
            return success(filePath);
        } catch (Exception e) {
            return error(I18nUtil.message(ExceptionConstants.DOWNLOAD_ERROR), e.getMessage());
        }
    }

    @GetMapping("/checkUnique")
    @ApiOperation(value = "检查字典是否重复")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "configId", name = "参数主键"),
            @ApiImplicitParam(value = "configName", name = "参数名称"),
            @ApiImplicitParam(value = "configKey", name = "参数Key")
    })
    public Valid checkUnique() {
        String configId = getRequest().getParameter("configId");
        String configName = getRequest().getParameter("configName");
        String configKey = getRequest().getParameter("configKey");
        boolean result = true;
        Valid valid = new Valid();
        if (StringUtil.isNotEmpty(configName))
            result = tbSysConfigService.checkConfigNameUnique(Convert.toLong(configId), configName);
        if (StringUtil.isNotEmpty(configKey))
            result = tbSysConfigService.checkConfigKeyUnique(Convert.toLong(configId), configKey);

        valid.setValid(result);
        return valid;
    }
}
